using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MediatR;
using RBAC.Domain.Dto.Output;
using RBAC.Read.Api.Application.Command.ERP.OutboundManagement;
using RBAC.Read.Api.Application.Dto.ERP;
using RBAC.ErrorCode;

namespace RBAC.Read.Api.Controllers.ERP
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class OutboundManagementController : ControllerBase
    {
        private readonly IMediator mediator;

        public OutboundManagementController(IMediator mediator)
        {
            this.mediator = mediator;
        }
        /// <summary>
        /// 销售出库分页
        /// </summary>
        [HttpGet]
        public async Task<APIPaging<SalesOutboundListDto>> GetSalesOutboundPage([FromQuery] GetSalesOutboundPageCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await mediator.Send(request, cancellationToken);
            }
            catch (Exception ex)
            {
                return new APIPaging<SalesOutboundListDto>
                {
                    Code = APIEnums.Error,
                    Msg = $"获取销售出库分页失败: {ex.Message}",
                    PageDatas = new List<SalesOutboundListDto>(),
                    TotalCount = 0
                };
            }
        }

        /// <summary>
        /// 根据ID获取销售出库详情（含明细与物料信息）
        /// </summary>
        [HttpGet("{id}")]
        public async Task<APIResult<SalesOutboundDetailDto>> GetSalesOutboundDetailById(long id, CancellationToken cancellationToken)
        {
            try
            {
                var command = new GetSalesOutboundByIdCommand { Id = id };
                return await mediator.Send(command, cancellationToken);
            }
            catch (Exception ex)
            {
                return new APIResult<SalesOutboundDetailDto>
                {
                    Code = APIEnums.Error,
                    Msg = $"获取销售出库详情失败: {ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 根据销售订单ID获取物料列表
        /// </summary>
        [HttpGet("{salesOrderId}")]
        public async Task<APIResult<List<MaterListDto>>> GetMaterListBySalesOrderId( long salesOrderId, CancellationToken cancellationToken)
        {
            try
            {
                var command = new GetMaterListBySalesOrdeIdCommand { SalesOrderId = salesOrderId };
                return await mediator.Send(command, cancellationToken);
            }
            catch (Exception ex)
            {
                return new APIResult<List<MaterListDto>>
                {
                    Code = APIEnums.Error,
                    Msg = $"获取物料列表失败: {ex.Message}",
                    Data = new List<MaterListDto>()
                };
            }
        }
    }
}
